package com.dicsystems.myrec;

import java.util.List;

import com.dicsystems.myrec.dto.Todo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;

public class TodoAdapter extends ArrayAdapter<Todo> implements SectionIndexer {

	private LayoutInflater inflater;
	private int resource;

	protected TodoAdapter(Context context, int resource, List<Todo> todos) {
		super(context, resource, todos);
		this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.resource = resource;
	}

	private static class ViewHolder {
		TextView start_date;
		TextView start_time;
		TextView end_date;
		TextView end_time;
		TextView title;
		TextView category;
		TextView memo;
		TextView place;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null || convertView.getId() != R.layout.list_title) {
			convertView = inflater.inflate(resource, null);
			holder = new ViewHolder();
			holder.start_date = (TextView)convertView.findViewById(R.id.start_date);
			holder.start_time = (TextView)convertView.findViewById(R.id.start_time);
			holder.end_date = (TextView)convertView.findViewById(R.id.end_date);
			holder.end_time = (TextView)convertView.findViewById(R.id.end_time);
			holder.title = (TextView)convertView.findViewById(R.id.title);
			holder.category = (TextView)convertView.findViewById(R.id.category);
			holder.memo = (TextView)convertView.findViewById(R.id.memo);
			holder.place = (TextView)convertView.findViewById(R.id.place);
			convertView.setTag(holder);
		}
		else {
			holder = (ViewHolder)convertView.getTag();
		}
		Todo todo = getItem(position);
		if(!isEnabled(position)) {
			convertView =  inflater.inflate(R.layout.list_title, null);
			TextView title = (TextView)convertView.findViewById(R.id.title);
			title.setText(todo.start_date);
		}
		else {
			holder.start_date.setText(todo.start_date);
			holder.start_time.setText(todo.start_time);
			holder.end_date.setText(todo.end_date);
			holder.end_time.setText(todo.end_time);
			holder.title.setText(todo.title);
			holder.category.setTag(todo.category_id);
			holder.category.setText(todo.category_name);
			if(todo.memo.equals("")) {
				holder.memo.setVisibility(View.GONE);
			}
			else {
				holder.memo.setText(todo.memo);
			}
			holder.place.setText(todo.place);
		}
		return convertView;
	}

	@Override
	public boolean isEnabled(int position) {
		return getItem(position).id != null;
	}

	@Override
	public int getPositionForSection(int section) {
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		return 0;
	}

	@Override
	public Object[] getSections() {
		return null;
	}
}
